const axios = require("axios");
const fs = require("fs");
const path = require("path");
const url = require("url");
const readline = require("readline");

const serverHost = "http://localhost:4000";
const outputPath = "./src/api";
const httpFolder = "../";

const getApiSdk = async (moduleName) => {
    moduleName = moduleName.toLowerCase();

    if (moduleName == "http") {
        rl.question("\x1b[33m如果你不是首次生成Http模块，那么它将被覆盖，建议保留自行备份，是否继续生成？\x1b[0m(y/N)", async (answer) => {
            if (answer.toLowerCase() === "y") {
                let arr = ["HttpClient.ts", "HttpRequest.ts", "HttpUtil.ts"];
                for (let i = 0; i < arr.length; i++) {
                    const item = arr[i];
                    let json = await axios.get(url.resolve(serverHost, "static/http/" + item));
                    let group = {
                        folder: "Http",
                        fileName: item,
                        content: json.data,
                    };
                    writeFile(group);
                }
            } else {
            }

            // 关闭 readline 接口
            rl.close();
        });
    } else {
        let json = await axios.get(url.resolve(serverHost, "static/sdk.json"));
        if (moduleName != "all") {
            if (!json.data.some((item) => item.folder.toLowerCase() == moduleName)) {
                console.log("\x1b[33m不存在的模块\x1b[0m");
                return;
            }
        }

        for (let i = 0; i < json.data.length; i++) {
            let group = json.data[i];
            if (moduleName == "all") {
                writeFile(group);
            } else if (moduleName == group.folder.toLowerCase()) {
                writeFile(group);
            }
        }
        rl.close();
    }
};

const writeFile = (group) => {
    let writePath = path.join(__dirname, outputPath, group.folder, group.fileName);
    // 获取目录路径
    const directory = path.dirname(writePath);
    try {
        fs.mkdirSync(directory, {
            recursive: true,
        });
        let content = group.content.replace("#HttpFolder#", httpFolder);
        fs.writeFileSync(writePath, content);
        console.log(`\x1b[32m已生成SDK模块:${writePath}\x1b[0m`);
    } catch (error) {
        console.log(error);
    }
};

// getApiSdk()
// 创建一个readline接口
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
});

// 提示用户输入
rl.question("\x1b[32m请输入你想拉取的模块名称，全部请输入all：\x1b[0m", (userInput) => {
    if (userInput.trim().length == 0) {
        console.log("\x1b[33m未输入名称，已退出指令\x1b[0m");
        rl.close();
    } else {
        getApiSdk(userInput);
    }
});
